use axum::{middleware, response::Response, routing::post, Json, Router};
use serde::Deserialize;
use serde_json::{json, Value};
use tower_cookies::{Cookie, Cookies};

use crate::{
    web::{self, AUTH_TOKEN},
    Error, Result,
};

pub fn routes() -> Router {
    Router::new()
        .route("/api/login", post(api_login))
        .layer(middleware::map_response(main_response_mapper))
}

async fn api_login(cookies: Cookies, payload: Json<LoginPayload>) -> Result<Json<Value>> {
    println!("--> {:<12} - api_login - {payload:?}", "HANDLER");

    // TODO: Implement real db/auth logic
    if payload.username != "jerry" || payload.password != "5852" {
        return Err(Error::LoginFail);
    }

    // FIXME: Implement real token logic
    cookies.add(Cookie::new(web::AUTH_TOKEN, "user-1.exp.sign"));

    // Create the success body
    let body = Json(json!({
        "result": {
        "success": true,
    }
    }));

    Ok(body)
}

async fn main_response_mapper(res: Response) -> Response {
    println!("->> {:12} - main_response_mapper", "RESP_MAPPER");

    println!();
    res
}

#[derive(Debug, Deserialize)]
struct LoginPayload {
    username: String,
    password: String,
}
